import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
import { BASE_URL, JWT_LS } from '../constants'
import { IToken } from '../model/interfaces'

export const getTokenFromLocalStorage = () => {
    return localStorage.getItem(JWT_LS)
}

export interface IUser {
    _id: string
    email: string
    name: string
    accessLevel: 'usual' | 'admin'
}
export interface ILogin {
    email: string
    password: string
}
export interface IUserUpdate {
    email: string
    name: string
}
export interface IRegister {
    email: string
    name: string
    password: string
    accessLevel:string
}

export const authApi = createApi({
    reducerPath: 'authApi',
    baseQuery: fetchBaseQuery(
        { baseUrl: `${BASE_URL}`}),
    endpoints: builder => ({
        signIn: builder.query<IToken, ILogin>({
            query: (loginData: ILogin) => ({
                method: 'POST',
                body: loginData,
                url: 'signin'
            }),
        }),
        signUp: builder.mutation<void, IRegister>({
            query: (user: IRegister) => ({
                method: 'POST',
                body: user,
                url: 'signUp'
            }),
        }),
        checkToken: builder.query<IUser, string>({
            query:(token) => ({
                method: 'GET',
                url: '/users/me',
                headers: {Authorization: `Bearer ${token}`}
            })
        })
    }),
})

export const {
    useLazySignInQuery,
    useSignUpMutation,
    useLazyCheckTokenQuery
} = authApi
